import Dialog from '@vant/weapp/dialog/dialog'
import Toast from '@vant/weapp/toast/toast'
import Notify from '@vant/weapp/notify/notify'
import { clearUserLocalStorage, userRequest } from '../../../../utils/util'
const { authorization } = require('../../../../utils/location')
const app = getApp()

Page({
  // 页面的初始数据
  data: {
    orders: [],
    markers: [],
    selected_ids: [],
    main_order_ids: [], //合并后数量
    select_all_status: false,
    max_upload_size: 1048576 * 2,
    scale: 12.1,
    activeNames: ['1'], // 打开信息 按钮
    latitude: 0, // 获取当前位置
    longitude: 0,
    checked: true,
    image: '/templates/deliver/img/business.png',
    current_order_id: '',
    current_order_no: '',
    current_order_remark: '',
    current_delivery_photo: [],
    // 是否显示面板指示点
    indicator_dots: true,
    autoplay: false, // 是否自动切换
    interval: 5000, // 自动切换时间间隔
    duration: 500, // 滑动动画时长
    color: '#ffffff', // 当前选中的指示点颜色
    height: '',
    level: 0,
    searchOrder: [],
    current_delivery_man_id: '',
    current_delivery_district_id: '',
    page: 1, // 页码
    size: 50, // 条数
    totalPages: 0, // 总页数
    isLoading: false,// 加载状态锁
    delivery_man: '',
    delivery_district_list: [],
  },

  // 生命周期函数--监听页面加载
  async onLoad(options) {
    // 检查登录有效期
    const now = Date.now() / 1000
    const expirationTime = app.session.expiration_time || 0
    if (now > expirationTime) {
      console.log('已过登录有效期!')
      app.session = {}
      clearUserLocalStorage()
      wx.reLaunch({
        url: '/pages/selectID/selectID'
      })
    }

    console.log('session:', app.session)

    // 从本地存储获取当前配送员 ID，若不存在则为 0
    let current_delivery_man_id = wx.getStorageSync('current_delivery_man_id') || 0
    // 从本地存储获取当前配送区域 ID，若不存在则为 0
    let current_delivery_district_id = wx.getStorageSync('current_delivery_district_id') || 0
    // 从 app 会话中获取配送员级别
    let level = wx.getStorageSync('level') || 0
    let delivery_district = wx.getStorageSync('delivery_district')
    let delivery_man_list = app.session.delivery_man_list
    let delivery_district_list = app.session.delivery_district_list
    let access_token = wx.getStorageSync('access_token')
    let delivery_man = app.session.user.delivery_man_id
    // 设置页面数据
    this.setData({
      access_token,
      delivery_man,
      delivery_district,
      delivery_district_list,
      delivery_man_list,
      current_delivery_district_id,
      level,
      current_delivery_man_id
      // 'current_delivery_district_id': current_delivery_man_id,
      // 'current_delivery_man_id': current_delivery_man_id
    })

    // 获取配送中的订单
    this.get_in_delivery()
  },
  // 处理选择订单事件
  onCheck(e) {
    const selectedIds = e.detail
    const mainOrderIds = this.data.main_order_ids
    console.log('selected_ids:', selectedIds)
    let selectAllStatus = false
    if (selectedIds.length === mainOrderIds.length) {
      selectAllStatus = true
    }
    this.setData({
      selected_ids: selectedIds,
      select_all_status: selectAllStatus
    })
  },

  onSearchChange(e) {
    let search_mobile = e.detail.replace(/\s+/g, '')
    // 验证手机号格式
    let mobilePattern = /^1[3-9]\d{9}$/
    if (!search_mobile) {
      this.setData({
        orders: this.data.searchOrder
      })
      this.data.searchOrder = [] // 清空备份
    } else {
      if (!mobilePattern.test(search_mobile)) {
        Toast.fail('请输入正确的手机号')
        return
      }
      if (this.data.searchOrder.length === 0) {
        // 首次搜索时备份原始数据
        this.data.searchOrder = [...this.data.orders]
      }
      // const allOrders = this.data.orders;
      const filteredOrders = this.data.orders.filter(order => {
        // 假设订单中有 mobile 和 contact 字段分别表示手机号和用户名
        return order.mobile.includes(search_mobile)
      })
      this.setData({
        orders: filteredOrders
      })
    }
  },
  onClearChange(e) {
    if (this.data.searchOrder.length > 0) {
      // 恢复备份数据
      this.setData({
        orders: this.data.searchOrder
      })
      this.data.searchOrder = [] // 清空备份
    }
  },


  // 解析 JSON 字符串为数组
  parseJsonOrEmptyArray(jsonString) {
    try {
      const parsed = JSON.parse(jsonString)
      if (Array.isArray(parsed)) {
        // 检查数组元素的结构，并进行转换
        return parsed.map(item => {
          if (typeof item === 'object' && 'url' in item) {
            return item // 已经是 { url: 'https://xxxxx' } 格式
          } else if (typeof item === 'object' && item.url) {
            return item.url // 处理 { url: { url: 'https://xxxxx' } } 格式
          } else {
            return {} // 无效的对象格式，返回空对象
          }
        })
      } else {
        return []
      }
    } catch (e) {
      return []
    }
  },

  // 处理弹框显示事件
  // ballPopup(e) {
  //     const index = parseInt(e.currentTarget.dataset.index);
  //     const currentOrderId = e.currentTarget.dataset.order_id; // 获取传递的 id 参数
  //     const currentOrder = this.data.orders[index];
  //     currentOrder.delivery_photo = this.parseJsonOrEmptyArray(currentOrder.delivery_photo);
  //     this.setData({
  //         show_popup: true,
  //         current_order_id: currentOrderId,
  //         current_order: currentOrder
  //     }); // 打开弹窗
  // },

  // 处理弹框关闭事件
  // onPopupClose() {
  //     this.setData({
  //         show_popup: false,
  //     });
  // },

  // 处理头像点击事件
  tap_avatar(e) {
    console.log(e)
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
    const latitude = e.currentTarget.dataset.latitude // 获取传递的 id 参数
    const longitude = e.currentTarget.dataset.longitude // 获取传递的 id 参数
    this.setData({
      scale: 17
    })
    this.map = wx.createMapContext('locationM', this)
    this.map.moveToLocation({
      longitude: Number(longitude),
      latitude: Number(latitude),
      success: () => {
        console.log('成功将地图中心移到定位点')
      }
    })
  },

  // // 处理全选事件
  // select_all(event) {
  //     const mainOrderIds = this.data.main_order_ids;
  //     let selectedIds = [];
  //     if (event.detail) {
  //         for (let i = 0; i < mainOrderIds.length; i++) {
  //             selectedIds.push(String(mainOrderIds[i]));
  //         }
  //     }
  //     this.setData({
  //         selected_ids: selectedIds,
  //         select_all_status: event.detail,
  //     });
  // },

  // 处理配送区域下拉框改变事件
  on_delivery_district_dropdown_change(e) {
    const current_delivery_man_id = e.detail
    this.setData({
      current_delivery_district_id: current_delivery_man_id,

    })
    wx.setStorageSync('current_delivery_district_id', current_delivery_man_id)
    this.get_in_delivery()
  },

  // 处理配送人员下拉框改变事件
  on_delivery_dropdown_change(e) {
    const current_delivery_man_id = e.detail
    this.setData({
      current_delivery_man_id: current_delivery_man_id
    })
    wx.setStorageSync('current_delivery_man_id', current_delivery_man_id)
    this.get_in_delivery()
  },

  // 获取当前位置
  async get_current_location() {
    const res = await authorization()
    console.log('authorization res', res)
    this.setData({
      longitude: res.longitude,
      latitude: res.latitude
    })
  },

  // 处理备注输入事件
  // onRemarkInput(e) {
  //     const value = e.detail;
  //     const currentOrder = this.data.current_order;
  //     currentOrder.delivery_remark = value;
  //     this.setData({
  //         current_order: currentOrder
  //     });
  // },

  // 提交订单备注
  // submit_wms_order_remark() {
  //     const currentOrder = this.data.current_order;

  //     wx.request({
  //         url: app.globalData.API + '/delivery/index/remark-delivery-order',
  //         header: {
  //             'Content-Type': 'application/json',
  //             "x-api-key": this.data.access_token,
  //         },
  //         method: "POST",
  //         data: {
  //             current_order: currentOrder
  //         },
  //         success: (res) => {
  //             if (res.data.code === 200) {
  //                 Toast('提交成功~');
  //                 this.onPopupClose();
  //             } else {
  //                 Toast('提交失败~');
  //             }
  //         }
  //     });
  // },

  // 生命周期函数--监听页面初次渲染完成
  onReady() {
    // 可在此添加页面初次渲染完成后的逻辑
  },

  // 生命周期函数--监听页面显示
  onShow() {
    // 可在此添加页面显示时的逻辑
  },

  // 生命周期函数--监听页面隐藏
  onHide() {
    // 可在此添加页面隐藏时的逻辑
  },

  // 生命周期函数--监听页面卸载
  onUnload() {
    // 可在此添加页面卸载时的逻辑
  },

  // 处理显示开关事件
  // onDisplay({ detail }) {
  //     console.log({ detail });
  //     const markers = this.data.markers;
  //     wx.showModal({
  //         title: '提示',
  //         content: '是否切换开关？',
  //         success: (res) => {
  //             console.log(res.confirm);
  //             if (!detail) {
  //                 for (let i = 0; i < markers.length; i++) {
  //                     this.setData({
  //                         [`markers[${i}].callout.display`]: 'BYCLICK',
  //                         checked: detail
  //                     });
  //                 }
  //                 this.setData({
  //                     checked: detail
  //                 });
  //             } else {
  //                 for (let i = 0; i < markers.length; i++) {
  //                     this.setData({
  //                         [`markers[${i}].callout.display`]: 'ALWAYS',
  //                     });
  //                 }
  //                 this.setData({
  //                     checked: detail
  //                 });
  //             }
  //         },
  //     });
  // },

  // 处理显示标注信息切换事件
  // onChangeShowCallout(event) {
  //     const { value } = event.detail;
  //     console.log(value);
  //     this.data.markers.forEach((item, index) => {
  //         if (value) {
  //             this.setData({
  //                 [`markers[${index}].callout.display`]: 'ALWAYS'
  //             });
  //         } else {
  //             this.setData({
  //                 [`markers[${index}].callout.display`]: 'BYCLICK'
  //             });
  //         }
  //     });
  // },

  // 点击展开订单详情
  // onOrder(e) {
  //     this.setData({
  //         activeNames: e.detail,
  //     });
  //     // this.get_waiting_goods(order_no)
  // },

  // 查询订单信息
  queryOrder(e) {
    const orderNo = e.currentTarget.dataset.order_no
    this.getViewOrderInfo(orderNo)
  },

  // 获取订单详细信息
  async getViewOrderInfo(orderNo) {
    const header = {
      'Content-Type': 'application/json',
      'x-api-key': this.data.access_token
    }
    const data = {
      order_no: orderNo
    }
    const url = app.globalData.API + '/delivery/index/query-order-info'
    const res = await userRequest(url, 'POST', data, header)
    if (res.code === 200) {
      const success = res.data
      if (success) {
        const orderInfo = JSON.stringify(res.data)
        console.log('orderInfo:', orderInfo)
        wx.navigateTo({
          url: '/templates/deliver/pages/orderInfo/orderInfo',
          success: res => {
            res.eventChannel.emit('orderInfo', orderInfo)
          }
        })
      }
    }
    // wx.request({
    //     url: app.globalData.API + '/delivery/index/query-order-info',
    //     header: {
    //         'Content-Type': 'application/json',
    //         "x-api-key": this.data.access_token,
    //     },
    //     method: "POST",
    //     data: {
    //         order_no: orderNo
    //     },
    //     success: (res) => {
    //         console.log(res)
    //         if (res.data.code === 200) {
    //             const success = res.data.data;
    //             if (success) {
    //                 const orderInfo = JSON.stringify(res.data.data);
    //                 console.log('orderInfo:', orderInfo);
    //                 wx.navigateTo({
    //                     url: '/templates/deliver/pages/orderInfo/orderInfo',
    //                     success: (res) => {
    //                         res.eventChannel.emit('orderInfo', orderInfo);
    //                     }
    //                 });
    //             }
    //         }
    //     }
    // });
  },

  // 送达选中的订单
  // async deliver_selected() {
  //     const selectedIds = this.data.selected_ids;
  //     await this.finish_deliver(selectedIds);
  // },

  // 送达单个订单
  async deliver(e) {
    const contact = e.currentTarget.dataset.contact
    const orderId = e.currentTarget.dataset.order_id // 获取传递的 id 参数
    const orderIds = []
    console.log(e)
    Dialog.confirm({
      title: '确认送达',
      message: `确定 ${contact} 的订单已经送达`
    })
      .then(() => {
        orderIds.push(orderId)
        this.finish_deliver(orderIds)
      })
      .catch(() => {
        // on cancel
        Notify({
          type: 'warning',
          message: '取消送达'
        })
      })
  },

  // 完成订单送达
  async finish_deliver(orderIds) {
    wx.request({
      url: app.globalData.API + '/delivery/index/finish-deliver',
      header: {
        'Content-Type': 'application/json',
        'x-api-key': this.data.access_token
      },
      method: 'POST',
      data: {
        order_ids: orderIds
      },
      success: res => {
        if (res.data.code === 200) {
          const success = res.data.data
          if (success) {
            wx.showToast({
              title: '成功',
              icon: 'success',
              duration: 2000
            })
            this.get_in_delivery()
          }
        }
      }
    })
  },

  // 拨打电话
  call_mobile(e) {
    const mobile = e.currentTarget.dataset.mobile
    console.log(mobile)
    wx.makePhoneCall({
      phoneNumber: mobile,
      success: () => {
        console.log('拨打电话成功！')
      },
      fail: () => {
        console.log('拨打电话失败！')
      }
    })
  },

  // 获取配送中的订单
  async get_in_delivery() {
    const deliveryStatus = 1
		const { page, size } = this.data

		if (page === 1) {
      this.setData(Object.assign({}, this.data, {
        orders: [],
        main_order_ids: [],
        markers: [],
        selected_ids: []
      }));
    }
    await this.get_current_location()
    wx.request({
      url: app.globalData.API + '/delivery/index/get-in-delivery-orders',
      header: {
        'Content-Type': 'application/json',
        'x-api-key': this.data.access_token
      },
      method: 'POST',
      data: {
        current_delivery_district_id: this.data.current_delivery_district_id,
        current_delivery_man_id: this.data.current_delivery_man_id,
        delivery_status: deliveryStatus,
        page,
        size
      },

      success: res => {
        console.log(res)
        if (res.data.code === 200) {
          console.log(res.data.data.orders)
          console.log(this.data.orders)
          const newOrders = res.data.data.orders
          const maxDistance = res.data.data.max_distance
          const total = res.data.data.pagination.total_pages
          const newMarkers = []
          for (let i = 0; i < newOrders.length; i++) {
            const longitude = newOrders[i].longitude // 经度
            const latitude = newOrders[i].latitude // 纬度
            newOrders[i].latitude = latitude
            newOrders[i].longitude = longitude
            newOrders[i].delivery_merge_id = parseInt(newOrders[i].delivery_merge_id)
            newOrders[i].distance = this.getDistance(
              latitude,
              longitude,
              this.data.latitude,
              this.data.longitude
            )
          }
          newOrders.sort((a, b) => a.distance - b.distance)
          const mainOrderIds = []
          for (let i = 0; i < newOrders.length; i++) {
            if (newOrders[i].delivery_merge_id === 0) {
              mainOrderIds.push(newOrders[i].order_id)
              newMarkers.push({
                iconPath: '../../img/icon-hc.png',
                id: 900000000 + parseInt(newOrders[i].order_id),
                order_id: newOrders[i].order_id,
                select_id: `#card-${newOrders[i].order_id}`,
                latitude: newOrders[i].latitude,
                longitude: newOrders[i].longitude,
                width: 23,
                height: 23,
                nearbyCount: 0,
                nearMarkers: [],
                nearMarkersInfo: [],
                callout: {
                  content: `${newOrders[i].contact} ${i + 1}`,
                  store_name: newOrders[i].contact,
                  fontSize: 14,
                  padding: true,
                  color: '#444',
                  display: 'ALWAYS',
                  textAlign: 'center',
                  borderRadius: 5,
                  bgColor: '#ffffff'
                }
              })
            }
          }
          // 计算每两个定位点之间的距离
          for (let i = 0; i < newMarkers.length; i++) {
            for (let j = i + 1; j < newMarkers.length; j++) {
              const distance = this.calculateDistance(
                newMarkers[i].latitude,
                newMarkers[i].longitude,
                newMarkers[j].latitude,
                newMarkers[j].longitude
              )
              if (distance <= maxDistance) {
                newMarkers[i].nearbyCount += 1
                newMarkers[j].nearbyCount += 1
                newMarkers[i].nearMarkers.push(newMarkers[j].id)
                newMarkers[j].nearMarkers.push(newMarkers[i].id)
                newMarkers[i].nearMarkersInfo.push({ distance: maxDistance - distance })
              }
            }
          }
          newMarkers.forEach(marker => {
            marker.callout.content += ` (${marker.nearbyCount})`
          })
          // console.log([...res.data.data.orders, ...this.data.orders])
          this.setData({
            markers: [...newMarkers, ...this.data.markers], //地图显示的标记点
            orders: [...newOrders, ...this.data.orders], //总订单数
            selected_ids: [], //选中的订单
            main_order_ids: [...this.data.main_order_ids, ...mainOrderIds], //主订单
            total //总页数
          })
          Notify({
            type: 'success',
            message: '数据加载完成'
          })
        }
      }
    })
  },

  // 根据距离排序订单
  sort_orders(orders) {
    const arr = [...orders]
    for (let i = 1; i < arr.length; i++) {
      for (let j = i; j > 0; j--) {
        if (arr[j].distance > arr[j - 1].distance) {
          const temp = arr[j]
          arr[j] = arr[j - 1]
          arr[j - 1] = temp
        }
      }
    }
    return arr.reverse()
  },

  // 经纬度计算距离
  getDistance(lat1, lng1, lat2, lng2) {
    const radLat1 = (lat1 * Math.PI) / 180.0
    const radLat2 = (lat2 * Math.PI) / 180.0
    const a = radLat1 - radLat2
    const b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0
    let s =
      2 *
      Math.asin(
        Math.sqrt(
          Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
        )
      )
    s = s * 6378.137 // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000
    s = s.toFixed(2)
    return parseFloat(s)
  },

  // 计算两点之间的距离
  calculateDistance(lat1, lon1, lat2, lon2) {
    const toRad = x => (x * Math.PI) / 180
    const R = 6371 // 地球半径（公里）
    const dLat = toRad(lat2 - lat1)
    const dLon = toRad(lon2 - lon1)
    const a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2)
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
    const distance = R * c
    return distance * 1000 // 转换为米
  },

  onTapMarker(e) {
    const markerId = parseInt(e.detail.markerId)
    const markers = this.data.markers;

    console.log(markerId)
    const marker = markers.find(m => m.id === markerId); // 根据地图标记的 id 找到对应的 marker
    console.log(marker)
    if (marker) {
      const query = wx.createSelectorQuery();
      console.log(query)
      query.select(marker.select_id).boundingClientRect(); // 根据订单 id 找到对应的卡片
      query.exec(function (res) {
        console.log('res', res)
        const cardRect = res[0];
        if (cardRect) {
          wx.pageScrollTo({
            scrollTop: cardRect.top,
          });
        }
      });
    } else {
      console.log('未找到对应订单')
    }
  },
  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh() {
    // console.log('下拉更新');
    this.setData({
      page: 1, // 重置页码为 1
      orders: [], // 清空订单数组
      main_order_ids: [] // 清空主订单数组
    })
    // console.log(this.data.orders)
    this.get_in_delivery()
    wx.stopPullDownRefresh()
  },

  // 页面上拉触底事件的处理函数
  onReachBottom() {
    const { page, total } = this.data
    if (page < total) {
      this.setData({
        page: page + 1 // 增加页码
      })
      this.get_in_delivery()
    } else {
      Notify({
        type: 'warning',
        message: '没有更多数据了'
      })
      this.setData({
        isLoading: true // 显示指定元素
      })
    }
  },

  // 用户点击右上角分享
  onShareAppMessage() {
    // 可在此添加分享相关逻辑
  },

  // 点击导航事件
  getLocation(e) {
    const index = e.currentTarget.dataset.index // 获取传递的参数
    const order = this.data.orders[index]
    const address = order.address
    const contact = order.contact
    const mobile = order.mobile
    const latitude = order.latitude
    const longitude = order.longitude
    wx.openLocation({
      latitude: Number(latitude), // 要去的纬度-地址 一定不要使数字
      longitude: Number(longitude), // 要去的经度-地址
      address: address,
      name: `${contact}/${mobile}`,
      scale: 15
    })
  },

  // 点击展开地址详情
  onAddress(event) {
    this.setData({
      activeNames: event.detail
    })
  },

  // 解绑订单
  onUnbind(e) {
    const current_delivery_man_id = this.data.delivery_man
    const contact = e.currentTarget.dataset.contact
    const orderId = e.currentTarget.dataset.order_id
    const orderNo = e.currentTarget.dataset.order_no
    Dialog.confirm({
      title: '解绑',
      message: `确定要解绑\n[${contact}] \n订单号: [${orderNo}] \n的订单？`
    })
      .then(() => {
        wx.request({
          url: app.globalData.API + '/delivery/index/unbind-order',
          header: {
            'Content-Type': 'application/json',
            'x-api-key': this.data.access_token
          },
          method: 'POST',
          data: {
            current_delivery_man_id: current_delivery_man_id,
            order_id: orderId
          },
          success: res => {
            if (res.data.code === 200) {
              Toast('解绑成功~')

              this.get_in_delivery()
            } else {
              Toast('解绑失败~')
            }
          }
        })
      })
      .catch(() => {
        // on cancel
        Toast('解绑失败~')
      })
  }

  // 关闭相关操作
  // onClose() {
  //     this.setData({
  //         fileList: [],
  //         values: '',
  //         ball: false,
  //         dshow: true,
  //     });
  // },

  // 跳转到订单详情页面
  // orderBydata(event) {
  //     const orderId = event.target.dataset.id;
  //     const name = event.target.dataset.name;
  //     wx.navigateTo({
  //         url: `/templates/deliver/pages/order/order?order_id=${orderId}&name=${name}`,
  //     });
  // }
})
